"""
简化版ffpyplayer视频播放器测试文件
使用QTimer而非单独线程来获取和显示视频帧
"""

import os
import sys
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("ffpyplayer_simple_test.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger("ffpyplayer_simple_test")

# 检查ffpyplayer是否安装
try:
    from ffpyplayer.player import MediaPlayer
    from ffpyplayer.tools import set_loglevel
    HAS_FFPYPLAYER = True
    # 设置ffpyplayer日志级别
    set_loglevel('warning')
except ImportError:
    HAS_FFPYPLAYER = False
    logger.error("未找到ffpyplayer库")

# 导入PyQt5组件
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QPushButton, QFileDialog, QHBoxLayout
from PyQt5.QtGui import QPixmap, QImage, QFont
from PyQt5.QtCore import QTimer, Qt


class SimpleVideoPlayer(QWidget):
    """
    简化版视频播放器
    使用QTimer获取和显示视频帧
    """
    def __init__(self, video_path=None, parent=None):
        super(SimpleVideoPlayer, self).__init__(parent)
        self.video_path = video_path
        self.player = None
        self.timer = None
        self.label = None
        self.play_button = None
        self.is_playing = False
        
        # 初始化UI
        self.init_ui()
        
        # 如果提供了视频路径，尝试加载视频
        if self.video_path:
            self.load_video(self.video_path)
    
    def init_ui(self):
        """初始化用户界面"""
        # 设置窗口属性
        self.setWindowTitle("简化版ffpyplayer视频播放器")
        self.setMinimumSize(800, 600)
        
        # 创建布局
        main_layout = QVBoxLayout()
        
        # 创建视频显示标签
        self.label = QLabel("视频将在这里显示")
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setStyleSheet("background-color: black; color: white;")
        self.label.setMinimumSize(640, 480)
        
        # 为标签设置字体，确保中文显示
        label_font = QFont()
        label_font.setFamily("SimHei")  # 黑体
        label_font.setPointSize(12)
        self.label.setFont(label_font)
        
        main_layout.addWidget(self.label)
        
        # 创建控制按钮
        control_layout = QHBoxLayout()
        
        # 按钮字体设置
        button_font = QFont()
        button_font.setFamily("SimHei")  # 黑体
        button_font.setPointSize(10)
        
        # 打开文件按钮
        open_button = QPushButton("打开文件")
        open_button.clicked.connect(self.open_file)
        open_button.setFont(button_font)  # 设置按钮字体
        control_layout.addWidget(open_button)
        
        # 播放/暂停按钮
        self.play_button = QPushButton("播放")
        self.play_button.clicked.connect(self.toggle_play_pause)
        self.play_button.setEnabled(False)  # 初始禁用
        self.play_button.setFont(button_font)  # 设置按钮字体
        control_layout.addWidget(self.play_button)
        
        # 停止按钮
        stop_button = QPushButton("停止")
        stop_button.clicked.connect(self.stop_playback)
        stop_button.setEnabled(False)  # 初始禁用
        stop_button.setFont(button_font)  # 设置按钮字体
        control_layout.addWidget(stop_button)
        
        main_layout.addLayout(control_layout)
        
        # 设置主布局
        self.setLayout(main_layout)
    
    def open_file(self):
        """打开视频文件对话框"""
        # 停止当前播放
        self.stop_playback()
        
        # 打开文件对话框
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择视频文件",
            ".",
            "视频文件 (*.mp4 *.avi *.mov *.mkv *.flv *.wmv)"
        )
        
        if file_path:
            self.load_video(file_path)
    
    def load_video(self, video_path):
        """加载视频文件"""
        try:
            # 验证文件
            if not os.path.exists(video_path):
                logger.error(f"文件不存在: {video_path}")
                return
            
            # 创建播放器
            self.player = MediaPlayer(video_path)
            self.video_path = video_path
            self.is_playing = False
            
            # 创建定时器
            self.timer = QTimer()
            self.timer.setInterval(30)  # 约33fps
            self.timer.timeout.connect(self.show_frame)
            
            # 更新UI状态
            self.setWindowTitle(f"简化版ffpyplayer视频播放器 - {os.path.basename(video_path)}")
            self.play_button.setEnabled(True)
            self.play_button.setText("播放")
            
            logger.info(f"成功加载视频: {video_path}")
            
        except Exception as e:
            logger.error(f"加载视频失败: {str(e)}")
            self.player = None
            self.timer = None
    
    def toggle_play_pause(self):
        """切换播放/暂停状态"""
        if not self.player:
            return
        
        if self.is_playing:
            # 暂停播放
            self.player.set_pause(True)
            self.timer.stop()
            self.play_button.setText("播放")
        else:
            # 开始播放
            self.player.set_pause(False)
            self.timer.start()
            self.play_button.setText("暂停")
        
        self.is_playing = not self.is_playing
    
    def stop_playback(self):
        """停止播放"""
        if self.timer:
            self.timer.stop()
            
        if self.player:
            self.player.close_player()
            self.player = None
            
        # 重置UI
        self.label.setText("视频将在这里显示")
        self.play_button.setEnabled(False)
        self.play_button.setText("播放")
        self.is_playing = False
    
    def show_frame(self):
        """显示视频帧"""
        if not self.player:
            return
        
        try:
            # 获取当前帧
            frame, val = self.player.get_frame()
            
            # 处理EOF
            if val == 'eof':
                logger.info("视频播放结束")
                self.stop_playback()
                return
            
            # 显示帧
            if frame is not None:
                img, t = frame
                if img is not None:
                    # 转换为QImage
                    w, h = img.get_size()
                    # 获取图像数据
                    if hasattr(img, 'to_bytearray'):
                        data = bytes(img.to_bytearray()[0])
                    elif hasattr(img, 'to_memoryview'):
                        data = img.to_memoryview()[0].tobytes()
                    else:
                        logger.error("无法获取图像数据")
                        return
                    
                    # 创建QImage并显示
                    qimg = QImage(data, w, h, QImage.Format_RGB888)
                    self.label.setPixmap(QPixmap.fromImage(qimg.scaled(
                        self.label.size(), 
                        Qt.KeepAspectRatio, 
                        Qt.SmoothTransformation
                    )))
                    
        except Exception as e:
            logger.error(f"显示帧失败: {str(e)}")
    
    def resizeEvent(self, event):
        """窗口大小改变时，调整视频显示大小"""
        super().resizeEvent(event)
        # 当窗口大小改变时，如果有正在播放的视频，重新显示当前帧以适应新大小
        if self.player and self.is_playing:
            self.show_frame()
    
    def closeEvent(self, event):
        """窗口关闭时，清理资源"""
        self.stop_playback()
        event.accept()


if __name__ == '__main__':
    # 检查ffpyplayer是否安装
    if not HAS_FFPYPLAYER:
        print("错误: 未安装ffpyplayer库")
        print("请先安装: pip install ffpyplayer")
        sys.exit(1)
    
    # 确保中文显示正常 - 增强版字体设置
    app = QApplication(sys.argv)
    
    # 设置全局字体
    font = QFont()
    font.setFamily("SimHei")  # 优先使用黑体
    font.setStyleStrategy(QFont.PreferDefault)  # 使用默认样式策略
    app.setFont(font)
    
    # 额外设置应用程序样式，确保在不同Windows版本上显示一致
    app.setStyle("Fusion")  # 使用Fusion样式，跨平台一致性更好
    
    # 检查命令行参数
    video_path = None
    if len(sys.argv) > 1:
        video_path = sys.argv[1]
        if not os.path.exists(video_path):
            logger.error(f"指定的视频文件不存在: {video_path}")
            video_path = None
    
    # 创建播放器窗口
    player = SimpleVideoPlayer(video_path)
    player.show()
    
    sys.exit(app.exec_())